﻿using System;
using System.Net.Mail;
using System.Text;
using System.Configuration;

namespace CSharpLogger.Product
{
    class EmailLogger : ILoggerHandler
    {
        #region [ Fields ]
        private static readonly EmailLogger _log2email = new EmailLogger();
        private string from;
        private string to;
        private string subject;
        private string body;
        private string cc;
        private string bcc;
        #endregion

        #region [ Properties ]
        public static EmailLogger Log2Email
        {
            get { return _log2email; }
        }

        public string AppName { get; set; }

        public string UserName { get; set; }

        public string Message { get; set; }

        public string Host { get; set; }

        public Level Level { get; set; } 
        #endregion

        #region [ Constructor ]
        private EmailLogger()
        {
            //from = ConfigurationManager.AppSettings["from"].ToString();
            to = ConfigurationManager.AppSettings["To"].ToString();
            cc = ConfigurationManager.AppSettings["CC"].ToString();
            bcc = ConfigurationManager.AppSettings["BCC"].ToString();
        }
        #endregion
        
        public void Log()
        {
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.UseDefaultCredentials = true;

            subject = string.Empty;
            
            MailMessage mail = new MailMessage();
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;
            
            
            mail.IsBodyHtml = true;
            mail.BodyEncoding = Encoding.ASCII;

            if (cc != string.Empty)
                mail.CC.Add(cc);
            if (bcc != string.Empty)
                mail.Bcc.Add(bcc);

            smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);

            try
            {
                //smtpClient.SendAsync(mail, mail.To);

                smtpClient.Send(mail);
            }
            catch (SmtpException e) { string error = e.ToString(); }
        }

        void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            string token = e.UserState.ToString();

            //TODO: Implement the use of MSMQ to know if the email has an error
            //if (e.Cancelled)
                
            //else if (e.Error != null)
                
            //else
                
        }        
    }
}
